<?php
/**
 * Created by PhpStorm.
 * User: zy-l
 * Date: 2019/6/19
 * Time: 1:23 AM
 */

namespace App\HttpController\Admin;

use App\HttpController\AdminBase;
use App\Model\InfoArticleClass;
use EasySwoole\Validate\Validate;

/**
 *  文章分类管理
 * Class InfoArticleClass
 * @package App\HttpController\Admin
 */
class Articleclass extends AdminBase
{

    /**
     * 公告模型
     * @return InfoArticleClass
     */
    public function getArticleClassModel()
    {
        return new InfoArticleClass();
    }

    /**
     * 首页
     * @return bool|string|void
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\Option
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function index()
    {
        if ($this->isPost()) {
            return $this->writePageJson('获取列表数据', $this->getArticleClassModel()->getPageAll([]));
        }
        $menu_list = $this->getArticleClassModel()->getMenuList([], 'id,name,pid as pId');
        $this->assign(['menu_list' => json_encode($menu_list)]);
        return $this->fetch('index');
    }

    /**
     * 编辑
     * @return bool|string|void
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function edit()
    {
        $id = $this->postParam('id');
        $info = $this->getArticleClassModel()->findOne(["id" => $id]);
        return $this->writeJson('操作成功', $info);
    }

    /**
     * 数据保存
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function save()
    {
        $data = $this->postParams();
        $data['pid'] = empty($data['pid']) ? 0 : $data['pid'];
        return $this->writeJson('操作成功', $this->getArticleClassModel()->updateOrCreateData($data, ["id" => $this->postParam("id")]));
    }

    /**
     * 选择顶级
     * @return string|void
     */
    public function show_select_menus()
    {
        $menuArr = $this->getArticleClassModel()->getMenuList([], 'id,name,pid as pId');
        $this->assign(["menu_list" => json_encode($menuArr)]);
        return $this->fetch();
    }

    public function del(){
        return $this->writeJson('删除成功',$this->getArticleClassModel()->delData(['id'=>$this->postParam('id')]));
    }

    /**
     * 提交参数验证
     * @param string|null $action
     * @return Validate|null
     */
    protected function getValidateRule(?string $action): ?Validate
    {
        $validate = null;
        return $validate;
    }
}